package com.education.platform.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.education.platform.common.Result;
import com.education.platform.dto.ai.*;
import com.education.platform.service.AiChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * AI聊天控制器
 */
@Tag(name = "AI聊天", description = "AI智能对话接口")
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiChatController {

    private final AiChatService aiChatService;

    @Operation(summary = "发送AI聊天消息")
    @PostMapping("/chat")
    @SaCheckLogin
    public Result<AiChatResponseDTO> chat(@Validated @RequestBody AiChatDTO chatDTO) {
        Long userId = StpUtil.getLoginIdAsLong();
        AiChatResponseDTO response = aiChatService.chat(chatDTO, userId);
        return Result.success(response);
    }

    @Operation(summary = "获取会话列表")
    @GetMapping("/conversations")
    @SaCheckLogin
    public Result<List<AiConversationVO>> getConversations() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<AiConversationVO> conversations = aiChatService.getConversations(userId);
        return Result.success(conversations);
    }

    @Operation(summary = "获取会话消息列表")
    @GetMapping("/conversations/{conversationId}/messages")
    @SaCheckLogin
    public Result<List<AiMessageVO>> getMessages(@PathVariable Long conversationId) {
        Long userId = StpUtil.getLoginIdAsLong();
        List<AiMessageVO> messages = aiChatService.getMessages(conversationId, userId);
        return Result.success(messages);
    }

    @Operation(summary = "创建新会话")
    @PostMapping("/conversations")
    @SaCheckLogin
    public Result<Long> createConversation(@RequestParam(required = false, defaultValue = "新对话") String title) {
        Long userId = StpUtil.getLoginIdAsLong();
        Long conversationId = aiChatService.createConversation(userId, title);
        return Result.success(conversationId);
    }

    @Operation(summary = "删除会话")
    @DeleteMapping("/conversations/{conversationId}")
    @SaCheckLogin
    public Result<Void> deleteConversation(@PathVariable Long conversationId) {
        Long userId = StpUtil.getLoginIdAsLong();
        aiChatService.deleteConversation(conversationId, userId);
        return Result.success();
    }
}

